//
//  LLHTTPUtil.m
//  lrlzapp
//
//  Created by dl on 16/2/25.
//  Copyright © 2016年 lrlz. All rights reserved.
//

#import "LLHTTPUtil.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "NSObject+LL.h"

@implementation LLHTTPUtil

+ (NSString *)networkType {
    NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    UIView *dataNetworkItemView = nil;

    for (id subview in subviews) {
        if ([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            dataNetworkItemView = subview;
            break;
        }
    }
    NSString *infoStr = nil;
    switch ([[dataNetworkItemView valueForKey:@"dataNetworkType"] integerValue]) {
        case 0:
            infoStr = @"无服务";
            break;
        case 1:
            infoStr = @"2G";
            break;
        case 2:
            infoStr = @"3G";
            break;
        case 3:
            infoStr = @"4G";
            break;
        case 4:
            infoStr = @"LTE";
            break;
        case 5:
            infoStr = @"WIFI";
            break;
        default:
            infoStr = @"无服务";
            break;
    }
    return infoStr;
}

+ (NSString *)getCarrierName {
    CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [telephonyInfo subscriberCellularProvider];
    NSString *currentCountry = [carrier carrierName];
    return currentCountry;
}

+ (NSString *)concactBaseUrlWithUrl:(NSString *)urlStr {
    NSURL *url = [NSURL URLWithString:urlStr];
    if (url.scheme) {
        return urlStr;
    }
    if ([URL_NEW_INTEFACE_ARR containsObject:urlStr]) {
        return [NSString stringWithFormat:@"%@%@", BD_HTTPS_BASE_URL_NEW, urlStr];
    }
    return [NSString stringWithFormat:@"%@%@", BD_HTTPS_BASE_URL_OLD, urlStr];
}

+ (NSString *)seq {
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *dateStr = [dateFormatter stringFromDate:date];

    int x = (arc4random() % 9000) + 1000;
    NSString *str = [NSString stringWithFormat:@"%@%d", dateStr, x];
    NSMutableString *tempStr = [NSMutableString stringWithString:[self getReverseString:str]];
    for (int i = 0; i < tempStr.length; ++i) {
        if ((i + 1) % 2 == 1) {
            NSString *eventStr = [tempStr substringWithRange:NSMakeRange(i, 1)];
            int x = 9 - [eventStr intValue];
            NSString *changeStr = [NSString stringWithFormat:@"%d", x];
            [tempStr replaceCharactersInRange:NSMakeRange(i, 1) withString:changeStr];
        }
    }
    return tempStr;
}

+ (NSString *)getReverseString:(NSString *)tempString {
    NSMutableString *mutableString = [NSMutableString string];
    for (int i = 0; i < tempString.length; ++i) {
        NSString *subStr = [tempString substringWithRange:NSMakeRange(tempString.length - i - 1, 1)];
        [mutableString appendString:subStr];
    }
    tempString = [NSString stringWithFormat:@"%@", mutableString];
    return tempString;
}

+ (NSDictionary *)getFinalParams:(NSDictionary *)params url:url {
    NSMutableDictionary *copyParams = [NSMutableDictionary dictionary];
    if (params) {
        [copyParams addEntriesFromDictionary:params];
    }

    // 只要token存在，都传递
    if (![[params allKeys] containsObject:@"token"] && [LLHTTPSessionManager shareManager].authenticated) {
        [copyParams setObject:[LLHTTPSessionManager shareManager].token forKey:@"token"];
    }

    [copyParams setObject:ClientVervion forKey:@"appVer"];
    [copyParams setObject:@"8681357557" forKey:@"appKey"];

    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    UIDevice *device = [UIDevice currentDevice];
    [copyParams setObject:[infoDict objectForKey:@"CFBundleShortVersionString"] forKey:@"cp[client_v]"];
    [copyParams setObject:@"ios" forKey:@"cp[platform]"];
    [copyParams setObject:[NSString stringWithFormat:@"%@", device.systemVersion] forKey:@"cp[platform_v]"];
    [copyParams setObject:[NSString stringWithFormat:@"%@", device.model] forKey:@"cp[model]"];
    [copyParams setObject:[SSKeychain UUID] forKey:@"cp[imei]"];

    int scale = ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0f);
    [copyParams setObject:[NSString stringWithFormat:@"%d*%d", [[NSNumber numberWithFloat:SCREEN_HEIGHT * scale] intValue], [[NSNumber numberWithFloat:FULL_WIDTH * scale] intValue]] forKey:@"cp[resolution]"];

    [copyParams setValue:@"AppStore" forKey:@"cp[channel]"];

    NSURL *urlToDocumentsFolder = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    __autoreleasing NSError *error;
    NSDate *installDate = [[[NSFileManager defaultManager] attributesOfItemAtPath:urlToDocumentsFolder.path error:&error] objectForKey:NSFileCreationDate];

    NSString *pathToInfoPlist = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSString *pathToAppBundle = [pathToInfoPlist stringByDeletingLastPathComponent];
    NSDate *updateDate = [[[NSFileManager defaultManager] attributesOfItemAtPath:pathToAppBundle error:&error] objectForKey:NSFileModificationDate];

    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *dateString = [fmt stringFromDate:installDate];
    [copyParams setValue:dateString forKey:@"cp[first_install]"];
    [copyParams setValue:[fmt stringFromDate:updateDate] forKey:@"cp[last_update]"];

    if (![[self networkType] isNullStr]) {
        [copyParams setValue:[[self networkType] urlEncodedString] forKey:@"cp[network]"];
    }
    if (![[self getCarrierName] isNullStr]) {
        [copyParams setValue:[[self getCarrierName] urlEncodedString] forKey:@"cp[operator]"];
    }

    [copyParams setObject:[self seq] forKey:@"seq"];

    return copyParams;
}

@end
